#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h> // close()
#include <arpa/inet.h> // inet_pton()
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8080
#define BUFFER_SIZE 1024

int main(){
    //1. 创建socket
    int server_fd  = socket(AF_INET,SOCK_STREAM, 0);
    if(server_fd < 0){
        perror("server socket create");
        exit(1);
    }
    //2. 绑定地址和端口
    struct sockaddr_in server_addr;
    int server_len = sizeof(server_addr);
    memset(&server_addr, 0,server_len);
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;
    int res = bind(server_fd,(struct sockaddr *)&server_addr, server_len);
    if(res < 0){
        perror("server bind");
        close(server_fd);
        exit(1);
    }

    //3. 监听连接
    res = listen(server_fd, 5);
    if(res < 0){
        perror("server listen");
        close(server_fd);
        exit(1);
    }

    //4. 接受连接
    struct sockaddr_in client_addr;
    int client_len = sizeof(client_addr);
    int new_socket;
    new_socket = accept(server_fd,(struct sockaddr*)&client_addr, &client_len);
    if(new_socket < 0){
        perror("server accept");
        close(server_fd);
        exit(1);
    }
    //5. 读取和写入数据
    char buffer[BUFFER_SIZE];
    int read_len = recv(new_socket,buffer,BUFFER_SIZE-1,0);
    if(read_len < 0){
        perror("server recv");
        close(new_socket);
        exit(1);
    }

    if(read_len == 0){
        printf("client close\n");
        close(new_socket);
        close(server_fd);
        exit(1);
    }

    buffer[read_len] = '\0';

    printf("recv client message: %s\n", buffer);

    char resp[1024]={0};
    snprintf(resp, 1023,"server receive: %s", buffer);

    int write_len = send(new_socket, resp, strlen(resp), 0);
    if(write_len < 0){
        perror("server send");
        close(new_socket);
        close(server_fd);
        exit(1);
    }

    printf("server send msg %s success!\n", resp);

    //6. 关闭socket
    close(new_socket);
    close(server_fd);
}